<template>
  <div class="workflow-container">
    <a-page-header title="工作流程管理" sub-title="查看并操作流程步骤">
      <template #extra>
        <a-button type="primary" @click="showCreateModal">新建流程</a-button>
      </template>
    </a-page-header>

    <a-card class="workflow-card">
      <!-- 流程步骤展示区 -->
      <a-steps :current="currentStep" class="workflow-steps" responsive>
        <a-step
          v-for="(step, index) in workflowSteps"
          :key="step.id"
          :title="step.title"
          :description="step.description"
          :status="getStepStatus(index)"
        >
          <template #icon>
            <custom-icon :type="step.icon" :status="getStepStatus(index)" />
          </template>
        </a-step>
      </a-steps>

      <!-- 当前步骤操作面板 -->
      <div class="step-operations">
        <h3>{{ currentStepData.title }} - 操作面板</h3>
        <p>{{ currentStepData.description }}</p>

        <div class="operation-buttons">
          <a-button
            v-for="action in currentStepData.actions"
            :key="action.name"
            :type="action.type"
            :loading="action.loading"
            @click="handleAction(action)"
            :disabled="!isActionEnabled(action)"
          >
            {{ action.label }}
          </a-button>
        </div>

        <!-- 步骤详情内容 -->
        <div class="step-content">
          <component :is="currentStepComponent" :step-data="currentStepData" @update="handleStepUpdate" />
        </div>
      </div>

      <!-- 流程操作历史 -->
      <a-divider orientation="left">操作记录</a-divider>
      <a-timeline class="operation-history">
        <a-timeline-item v-for="record in operationHistory" :key="record.id">
          <p>{{ record.operator }} 在 {{ formatTime(record.time) }} 执行了 {{ record.action }}</p>
          <p v-if="record.comment" class="comment">备注: {{ record.comment }}</p>
        </a-timeline-item>
      </a-timeline>
    </a-card>

    <!-- 新建流程模态框 -->
    <a-modal
      v-model:open="createModalVisible"
      title="新建工作流程"
      @ok="handleCreateWorkflow"
      @cancel="createModalVisible = false"
    >
      <a-form :model="newWorkflow" :label-col="{ span: 6 }">
        <a-form-item label="流程名称" required>
          <a-input v-model:value="newWorkflow.name" />
        </a-form-item>
        <a-form-item label="流程描述">
          <a-textarea v-model:value="newWorkflow.description" />
        </a-form-item>
        <a-form-item label="流程类型">
          <a-select v-model:value="newWorkflow.type">
            <a-select-option value="approval">审批流程</a-select-option>
            <a-select-option value="development">开发流程</a-select-option>
            <a-select-option value="testing">测试流程</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 步骤操作确认框 -->
    <a-modal
      v-model:open="confirmModal.visible"
      :title="confirmModal.title"
      @ok="confirmAction"
      @cancel="confirmModal.visible = false"
    >
      <p>{{ confirmModal.content }}</p>
      <a-textarea v-if="confirmModal.needComment" v-model:value="actionComment" placeholder="请输入操作备注" />
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, defineAsyncComponent } from "vue";
import { message } from "ant-design-vue";

// 异步加载步骤组件
const StepComponents = {
  approval: defineAsyncComponent(() => import("./compents/StepApproval.vue")),
  development: defineAsyncComponent(() => import("./compents/StepDevelopment.vue")),
};

// 工作流程数据
const workflowSteps = ref([
  {
    id: "1",
    title: "申请提交",
    description: "提交工作申请",
    icon: "file-add",
    status: "finish",
    component: "approval",
    actions: [
      { name: "edit", label: "编辑申请", type: "default" },
      { name: "submit", label: "提交申请", type: "primary" },
    ],
  },
  {
    id: "2",
    title: "主管审批",
    description: "等待主管审批",
    icon: "audit",
    status: "process",
    component: "approval",
    actions: [
      { name: "approve", label: "通过", type: "primary" },
      { name: "reject", label: "拒绝", type: "danger" },
      { name: "transfer", label: "转交", type: "default" },
    ],
  },
  {
    id: "3",
    title: "开发实施",
    description: "进行开发工作",
    icon: "code",
    status: "wait",
    component: "development",
    actions: [
      { name: "start", label: "开始开发", type: "primary" },
      { name: "report", label: "报告问题", type: "default" },
    ],
  },
  {
    id: "4",
    title: "测试验收",
    description: "测试功能验收",
    icon: "experiment",
    status: "wait",
    component: "testing",
    actions: [
      { name: "test", label: "执行测试", type: "primary" },
      { name: "report-bug", label: "报告缺陷", type: "danger" },
      { name: "approve", label: "验收通过", type: "primary" },
    ],
  },
  {
    id: "5",
    title: "部署上线",
    description: "部署到生产环境",
    icon: "cloud",
    status: "wait",
    component: "deployment",
    actions: [
      { name: "deploy", label: "执行部署", type: "primary" },
      { name: "rollback", label: "回滚", type: "danger" },
    ],
  },
]);

const currentStep = ref(1); // 当前步骤索引
const operationHistory = ref([
  {
    id: "1",
    operator: "张三",
    action: "提交申请",
    time: new Date("2023-05-10 09:30:00"),
    comment: "初始申请提交",
  },
  {
    id: "2",
    operator: "李四",
    action: "审批通过",
    time: new Date("2023-05-11 14:15:00"),
    comment: "符合要求，同意进行开发",
  },
]);

// 当前步骤数据
const currentStepData = computed(() => workflowSteps.value[currentStep.value]);
const currentStepComponent = computed(() => StepComponents[currentStepData.value.component]);

// 新建流程相关
const createModalVisible = ref(false);
const newWorkflow = ref({
  name: "",
  description: "",
  type: "approval",
});

// 操作确认相关
const confirmModal = ref({
  visible: false,
  title: "",
  content: "",
  action: null,
  needComment: false,
});
const actionComment = ref("");

// 获取步骤状态
const getStepStatus = (index) => {
  if (index < currentStep.value) return "finish";
  if (index === currentStep.value) return "process";
  return "wait";
};

// 格式化时间
const formatTime = (date) => {
  // return format(date, "yyyy-MM-dd HH:mm:ss");
};

// 显示新建流程模态框
const showCreateModal = () => {
  createModalVisible.value = true;
};

// 处理新建流程
const handleCreateWorkflow = () => {
  message.success("新建流程成功");
  createModalVisible.value = false;
  // 这里可以添加API调用
};

// 处理步骤操作
const handleAction = (action) => {
  // 需要确认的操作
  const needConfirmActions = ["reject", "transfer", "report-bug", "rollback"];

  if (needConfirmActions.includes(action.name)) {
    confirmModal.value = {
      visible: true,
      title: `确认${action.label}`,
      content: `您确定要${action.label}吗？此操作可能无法撤销。`,
      action: action,
      needComment: true,
    };
  } else {
    executeAction(action);
  }
};

// 确认操作
const confirmAction = () => {
  executeAction(confirmModal.value.action, actionComment.value);
  confirmModal.value.visible = false;
  actionComment.value = "";
};

// 执行操作
const executeAction = (action, comment = "") => {
  // 模拟操作处理
  message.loading({ content: "正在处理...", key: "action" });

  setTimeout(() => {
    // 更新操作历史
    operationHistory.value.unshift({
      id: Date.now().toString(),
      operator: "当前用户",
      action: action.label,
      time: new Date(),
      comment: comment,
    });

    // 根据操作类型更新流程状态
    switch (action.name) {
      case "submit":
      case "approve":
      case "start":
      case "test":
      case "deploy":
        if (currentStep.value < workflowSteps.value.length - 1) {
          currentStep.value++;
          workflowSteps.value[currentStep.value].status = "process";
        }
        break;
      case "reject":
        if (currentStep.value > 0) {
          currentStep.value--;
          workflowSteps.value[currentStep.value].status = "process";
        }
        break;
    }

    message.success({ content: "操作成功", key: "action", duration: 2 });
  }, 1000);
};

// 判断操作是否可用
const isActionEnabled = (action) => {
  // 这里可以根据业务逻辑添加判断条件
  return true;
};

// 处理步骤数据更新
const handleStepUpdate = (updatedData) => {
  // 更新步骤数据
  workflowSteps.value[currentStep.value] = {
    ...workflowSteps.value[currentStep.value],
    ...updatedData,
  };
  message.success("步骤数据已更新");
};
</script>

<style scoped>
.workflow-container {
  padding: 20px;
  max-height: 83vh;
  overflow-y: auto;
}

.workflow-card {
  margin-top: 20px;
}

.workflow-steps {
  margin-bottom: 40px;
}

.step-operations {
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-bottom: 30px;
}

.operation-buttons {
  margin: 20px 0;
}

.operation-buttons button {
  margin-right: 10px;
}

.step-content {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.operation-history {
  margin-top: 20px;
}

.comment {
  color: #888;
  font-size: 0.9em;
  margin-top: 5px;
}

.custom-icon {
  font-size: 24px;
}

.custom-icon[status="finish"] {
  color: #52c41a;
}

.custom-icon[status="process"] {
  color: #1890ff;
}

.custom-icon[status="wait"] {
  color: #d9d9d9;
}
</style>
